package lumis.portal.webservice.authentication;

import lumis.portal.PortalException;
import lumis.portal.authentication.IAuthenticationManager;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.webservice.WebServiceUtil;
import lumis.util.ITransaction;

/**
 * Web Service class for Authentication operations.
 *
 * @version $Revision: 11080 $ $Date: 2009-11-17 16:15:52 -0200 (Tue, 17 Nov 2009) $
 * @since 4.0.9
 */
public class AuthenticationService 
{
	/**
	 * Logins a user using the specified password as his credentials, and returns
	 * the new sessionId for the logged in user.
	 * If the login fail, this method throws a {@link PortalException}.
	 * @param login the user's login.
	 * @param password the user's password.
	 * @return the created sessionId
	 * @throws PortalException
	 */
	public String loginUser(String login, String password) throws PortalException
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try 
		{
			transaction.begin();
			
			SessionConfig sessionConfig = ManagerFactory.getAuthenticationManager().login(login, password, transaction);
			if (sessionConfig == null)
				throw new PortalException("Login failed.");
			String userSessionId = sessionConfig.getUserSessionId();
			
			transaction.commit();
			
			return userSessionId;
		} 
		finally 
		{
			transaction.dispose();
		}
	}

	/**
	 * Close the user's session given the sessionId.
	 * @param sessionId
	 * @throws PortalException
	 * @see {@link IAuthenticationManager#logoutUser(SessionConfig, ITransaction)}
	 */
	public void logoutUser(String sessionId) throws PortalException
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try {
			
			transaction.begin();
			SessionConfig sessionConfig = WebServiceUtil.getSessionConfig(sessionId, transaction);
			ManagerFactory.getAuthenticationManager().logoutUser(sessionConfig, transaction);
			transaction.commit();
		}
		finally 
		{
			transaction.dispose();
		}
		
	}
}
